package com.yuke.cloud.service.smc.controller.frontend;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.api.wmc.dto.WarehouseInfoDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.smc.dto.ShopDto;
import com.yuke.cloud.service.smc.entity.ExcelObject;
import com.yuke.cloud.service.smc.entity.Shop;
import com.yuke.cloud.service.smc.entity.ShopPayment;
import com.yuke.cloud.service.smc.service.ShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
* Created by wg on 2018/09/07.
*/
@Slf4j
@Api(value = "WEB - ShopController", tags = "处理Shop相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/shop")
public class  ShopController extends BaseController {
    @Resource
    private ShopService shopService;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Value("${yuke.shop.deliver_distance}")
    private Integer deliverDistance;


    /**
     * 导出 2天未下单的加盟店铺
     * @return
     */
    @RequestMapping(value = "/app", method = RequestMethod.GET)
    public Wrapper joinExcel(){
        List<ExcelObject> excelObjects = shopService.joinExcel();
        // 文件输出位置
        OutputStream out = null;
        try {
            out = new FileOutputStream("D:\\Excelout\\test.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(out);

            // 写仅有一个 Sheet 的 Excel 文件, 此场景较为通用
            Sheet sheet = new Sheet(1, 0, ExcelObject.class);
            // 第一个 sheet 名称
            sheet.setSheetName("第一个sheet");
            // 写数据到 Writer 上下文中
            // 入参1: 数据库查询的数据list集合
            // 入参2: 要写入的目标 sheet
            writer.write(excelObjects, sheet);

            // 将上下文中的最终 outputStream 写入到指定文件中
            writer.finish();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return WrapMapper.ok();
    }

    /**
     * 导出 2天未下单的活跃店铺
     * @return
     */
    @RequestMapping(value = "/app",method = RequestMethod.GET)
    public Wrapper activeShops(){
        List<ExcelObject> excelObjects = shopService.activeShops();
        // 文件输出位置
        OutputStream out = null;
        try {
            out = new FileOutputStream("D:\\Excelout\\test.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(out);

            // 写仅有一个 Sheet 的 Excel 文件, 此场景较为通用
            Sheet sheet = new Sheet(1, 0, ExcelObject.class);
            // 第一个 sheet 名称
            sheet.setSheetName("第一个sheet");
            // 写数据到 Writer 上下文中
            // 入参1: 数据库查询的数据list集合
            // 入参2: 要写入的目标 sheet
            writer.write(excelObjects, sheet);

            // 将上下文中的最终 outputStream 写入到指定文件中
            writer.finish();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try {
                // 关闭流
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return WrapMapper.ok();
    }





    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper<Shop> add(@ApiParam(name = "shop", value = "该数据记录的POJO") @RequestBody Shop shop) {

        int success = shopService.save(shop);

        if (success == -1){
            return WrapMapper.error("未找到对应地址信息，地址错误");
        }

        if (success == -2){
            return WrapMapper.error("您已申请过商家，请与联系客服");
        }

        if (success == -3) {
            return WrapMapper.error("您已申请过店铺或商家，请等待审核");
        }

        shop.setCreateStatus((byte)2);

        shop.setShopType((byte)1);

        return WrapMapper.ok(shop);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        shopService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "shop", value = "需要修改的内容") @RequestBody Shop shop) {
        int success = shopService.update(shop);
        if (success == -1){
            return WrapMapper.error("未找到对应地址信息，地址错误");
        }

        if (success == 0){
            return WrapMapper.error("记录未修改成功");
        }

        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<Shop> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        Shop shop = shopService.findById(id);
        return WrapMapper.ok(shop);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<Shop>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<Shop> list = shopService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }
    //
    //@GetMapping("/app/{userId}")
    //@ApiOperation(httpMethod = "GET", value = "根据userId获取该用户拥有的店铺")
    //public Wrapper<Shop> getByUserId(@ApiParam(name = "userId", value = "用户userId") @PathVariable Long userId) {
    //    Example example = new Example(Shop.class);
    //    Example.Criteria criteria = example.createCriteria();
    //    criteria.andEqualTo("userId", userId);
    //    List<Shop> shops = shopService.selectByExample(example);
    //    Shop shop = null;
    //    if (shops.size() > 0) {
    //        shop = shops.get(0);
    //    }
    //    return WrapMapper.ok(shop);
    //}

    /*@GetMapping("/app/nearShop")
    @ApiOperation(httpMethod = "GET", value = "获取附近所有店铺")
    public Wrapper<List<ShopDto>> findNearShops(@RequestParam("longitude") String longitude, @RequestParam("latitude") String latitude) {
        if (longitude == null || latitude == null) {
            return null;
        }
        List<ShopDto> shops = shopService.findNearShops(longitude, latitude, this.deliverDistance);
        return WrapMapper.ok(shops);
    }*/

    @PostMapping("/app/shopIds")
    @ApiOperation(httpMethod = "POST", value = "根据ID获取店铺信息")
    public Wrapper<List<ShopDto>> getShopInfo(@ApiParam(name = "shopIds", value = "记录shopIds") @RequestBody List<Long> shopIds) {
        List<ShopDto> shopDtos = shopService.findByIds(shopIds);
        return WrapMapper.ok(shopDtos);
    }

    @PostMapping("/payment")
    @ApiOperation(httpMethod = "POST",value = "店铺到期缴费管理")
    public Wrapper updatePayment(@ApiParam(name = "shopPayment",value = "缴费管理")@RequestBody ShopPayment shopPayment){

        return WrapMapper.ok();
    }

    @PostMapping("/condition")
    @ApiOperation(httpMethod = "POST", value = "根据地域Id和店铺名称获取店铺列表")
    public Wrapper<PageInfo<Shop>> getListDetailByCondition(@ApiParam(name = "id", value = "记录id") @RequestBody(required = false) ShopDto shopDto,
                                                            @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                            @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        //获得groupId,     WarehouseId在店铺审核前是没有的，用regionCityId，regionProvinceId查找
        Long groupId =4L;
        if (getGroupInfoDto() != null){
            groupId = getGroupInfoDto().getGroupId();
        }else {
            Long userId = getLoginAuthDto().getUserId();

            Wrapper<UserInfoDto> userInfoDtoWrapper = uacUserFeignApi.getUserInfoByUserId(userId);
            if (userInfoDtoWrapper != null && userInfoDtoWrapper.getCode() == 200) {
                if (userInfoDtoWrapper.getResult().getGroupId() != null) {
                    groupId = userInfoDtoWrapper.getResult().getGroupId();
                }

            } else {
                groupId = 220839532667469824L;
            }
        }
        if (groupId > 4){
            shopDto.setGroupId(groupId);
            List<WarehouseInfoDto> warehouseInfoDtos = wmcStorageFeignApi.getWarehouseInfoByGroupId(groupId);
            if (warehouseInfoDtos!=null && warehouseInfoDtos.size()>0){
                shopDto.setRegionCityId(warehouseInfoDtos.get(0).getRegionCityId());
                shopDto.setRegionProvinceId(warehouseInfoDtos.get(0).getRegionProvinceId());
            }
        }
        System.out.println("查询参数："+shopDto);
        List<Shop> list = shopService.getListDetailByCondition(shopDto);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/list")
    @ApiOperation(httpMethod = "POST", value = "根据店铺名称获取店铺列表")
    public Wrapper<List<Shop>> getListByCondition(@ApiParam(name = "id", value = "记录id") @RequestBody(required = false) Shop shop) {
        return WrapMapper.ok(shopService.getListByCondition(shop));
    }

    @GetMapping("/app/shopname")
    @ApiOperation(httpMethod = "GET", value = "获取直销店铺和直营店铺记录")
    public Wrapper<List<Shop>> shoplist() {
        Example example = new Example(Shop.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.orEqualTo("shopType", 3);
        criteria.orEqualTo("shopType", 4);

        List<Shop> list = shopService.selectByExample(example);

        return WrapMapper.ok(list);
    }


    /**
     * 将shopId和store关联起来
     */
    @PostMapping("/getShopIdToStore")
    @ApiOperation(httpMethod = "POST", value = "根据店铺名称获取店铺列表")
    public void getShopIdToStore(@ApiParam(name = "id", value = "记录id") @RequestBody(required = false) Shop shop) {

        shopService.getShopIdToStore(shop);
    }

    /**
     * 申请成为团长操作，待审核
     * @param shop
     * @return
     */
    @PostMapping("/teamApply")
    @ApiOperation(httpMethod = "POST", value = "修改一条记录")
    public Wrapper teamApply(@ApiParam(name = "shop", value = "需要修改的内容") @RequestBody Shop shop) {
        if (shop == null || shop.getTeamStatus() == null || shop.getUserId() == null ){
            return WrapMapper.error("参数错误！");
        }
        Shop shopApply = new Shop();
        shopApply.setUserId(shop.getUserId());
        shopApply.setTeamStatus((byte)1);
        int applyCount = shopService.selectCount(shopApply);
        if (applyCount > 0){
            return WrapMapper.error("店铺已经在申请中，请等待审核！");
        }

        int success = shopService.update(shop);

        if (success != 1){
            return WrapMapper.error("记录未修改成功");
        }

        return WrapMapper.ok();
    }

}
